package 快递单号查询;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by ZhuQianli on 2018/1/29.
 */
public class SearchExpress {

    public static void main(String[] args) throws IOException {
        String[] postIds = {"888246343680602379", "3831591637476"};

        for (String postId : postIds) {
            String data = getData(postId);
            System.out.println(data);
        }
    }

    public static String getData(String postId) throws IOException {
        String expressType = getExpressType(postId);
        String detail = getDetail(expressType, postId);

        return detail;
    }

    private static String getExpressType(String postId) throws IOException {
        String s = "";
        try {
            s = sendGet("http://www.kuaidi100.com/autonumber/autoComNum?resultv2=1&text=" + postId, null);
        } catch (Exception e) {
            System.out.println("retry");
            return getExpressType(postId);
        }
        try {
            JSONObject jsonObject = JSON.parseObject(s);
            JSONArray auto = jsonObject.getJSONArray("auto");
            String comCode = auto.getJSONObject(0).getString("comCode");

            return comCode;
        } catch (Exception e) {
            System.out.println(s);
            throw e;
        }
    }

    private static String getDetail(String type, String postId) throws IOException {
        for (int i = 0; i < 3; i++) {
            try {
                String detail = sendGet("http://www.kuaidi100.com/query?type=" + type + "&postid=" + postId + "&temp=0.20209314532872624", createHeaders());
                JSONObject jsonObject = JSON.parseObject(detail);
                String message = jsonObject.getString("message");
                String status = jsonObject.getString("status");
                String com = jsonObject.getString("com");
                if (!message.equals("ok") || !status.equals("200") || !com.equalsIgnoreCase(type)) {
                    continue;
                }
                return detail;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    private static String sendGet(String url, Header[] headers) throws Exception {
        CloseableHttpClient client = HttpClientBuilder.create().build();

        HttpGet httpGet = new HttpGet(url);

        if (headers != null) httpGet.setHeaders(headers);

        StringBuilder stringBuilder = new StringBuilder();
        try (CloseableHttpResponse execute = client.execute(httpGet)) {
            HttpEntity entity = execute.getEntity();
            InputStream content = entity.getContent();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(content, "UTF-8"));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line).append("\r\n");
            }
        } catch (Exception e) {
            throw e;
        }

        return stringBuilder.toString();
    }

    private static Header[] createHeaders() {
        List headersList = new ArrayList();
        headersList.add(new BasicHeader("accept", "application/json, text/javascript, */*; q=0.01"));
        headersList.add(new BasicHeader("accept-encoding", "gzip, deflate"));
        headersList.add(new BasicHeader("accept-language", "zh-CN,zh;q=0.9,en;q=0.8"));
        headersList.add(new BasicHeader("Referer", "http://www.kuaidi100.com/?from=openv"));
        Long s = System.nanoTime() % 100;
        Long s1 = System.nanoTime() % 100;
        headersList.add(new BasicHeader("user-agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537." + s + " (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537." + s1));

        return (Header[]) headersList.toArray(new Header[headersList.size()]);
    }

}
